package com.janko.springbootbase.juc.threadLocal;

/**
 * @Author janko
 * @Version 1.0
 * @date 2021/4/18 11:06
 * @Description  创建一个ThreadLocal变量，那么访问这个变量的每个线程都会有这个变量的一个副本，
 * 在实际多线程操作的时候，操作的是自己本地内存中的变量，从而规避了线程安全问题
 */
public class MyThreadLock {
    static ThreadLocal<String> localVar=new ThreadLocal<>();
    static void myPrint(String str){
        //打印当前线程中本地内存中本地变量的值
        System.out.println(str + ":" + localVar.get());
        localVar.remove();
    }

    public static void main(String[] args) {
        Thread thread1 =new Thread(new Runnable() {
            @Override
            public void run() {
                //设置thread1的值
                localVar.set("localVar1");
                myPrint("thread1");
                System.out.println("after remove:" + localVar.get());
            }
        });
        thread1.start();

        Thread thread2 =new Thread(new Runnable() {
            @Override
            public void run() {
                //设置thread1的值
                localVar.set("localVar2");
                myPrint("thread2");
                System.out.println("after remove:" + localVar.get());
            }
        });
        thread2.start();
    }
}
